﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project.Ycm20250401.Service._20250418.Domain.Entities
{
    /// <summary>
    /// 订单
    /// </summary>
    public class Order20250422
    {
        public string OrderId { get; private set; }
        public DateTime OrderDate { get; private set; }
        /// <summary>
        /// 
        /// </summary>
        public OrderStatus State { get; private set; }
        /// <summary>
        /// 
        /// </summary>
        public string UserId { get; private set; }
        /// <summary>
        /// 
        /// </summary>
        public decimal TotalAmount { get; private set; }
        /// <summary>
        /// 
        /// </summary>
        private readonly List<OrderItem> _items = new List<OrderItem>();
        /// <summary>
        /// 
        /// </summary>
        public IReadOnlyCollection<OrderItem> Items => _items;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="orderId"></param>
        public Order20250422(string orderId)
        {
            OrderId = orderId;
        }

        //下单方法
        public Order20250422 CreateOrder(string userId, IEnumerable<OrderItem> items)
        {
            //加入对库存的判断

            OrderId = Guid.NewGuid().ToString();
            OrderDate = DateTime.Now;
            State = 0;
            UserId = UserId;
            _items.AddRange(items);
            CalculateTotalAmount();
            return this;
        }

        //计算总金额
        private void CalculateTotalAmount()
        {
            TotalAmount = Items.Sum(item => item.Quantity * item.Price);
        }

        //支付方法
        public void Pay(decimal amount, string transactionId)
        {
            if (State != OrderStatus.Pending)
            {
                throw new ArgumentException("当前状态不支持支付");
            }

            if (amount != TotalAmount)
            {
                throw new ArgumentException("请重新核对金额");
            }
            State = OrderStatus.Paid;
        }
        //取消订单方法
        public void Cancel()
        {
            if (State != OrderStatus.Pending)
            {
                throw new ArgumentException("订单不能取消");
            }
            State = OrderStatus.Cancelled;
        }
    }

    /// <summary>
    /// 订单项
    /// </summary>
    /// <param name="ItemId"></param>
    /// <param name="Quantity"></param>
    /// <param name="Price"></param>
    public record OrderItem(string ItemId, int Quantity, decimal Price);


    // 订单状态枚举
    public enum OrderStatus
    {
        Pending,    // 待支付
        Paid,       // 已支付
        Shipped,    // 已发货
        Completed,  // 已完成
        Cancelled   // 已取消
    }
}
